import { unlinkSync, writeFileSync, existsSync, statSync, mkdirSync, readFileSync } from "fs";
import { sep, join, dirname } from "path";
import { getAllFiles } from "./utils/FileUtil";
var crtTime = 0;

function createDirSync(dirPath: string, callback?: () => void) {
    if (existsSync(dirPath)) {
        if (!!callback) {
            callback();
        }
    } else {
        createDirSync(dirname(dirPath), () => {
            mkdirSync(dirPath);
            if (!!callback) {
                callback();
            }
        });
    }
}

/**
 * 合成文件
 * @param fileUrls 所有需要合并的资源路径
 * @param out 最终输出文件的路径
 */
export function mergeFiles(fileUrls: string[], out: string, baseUrl: string, prefix: string, fn: string, delFile: string, outType: string, size: number) {
    prefix = prefix || '';
    delFile = delFile.toLowerCase() || 'false';
    let needDelFile = delFile == 'true' ? true : false;
    fn = fn || 'd3file.json';
    size = size || Number.MAX_SAFE_INTEGER;
    outType = outType || 'json';
    crtTime = Date.now();
    let mergedObj = {}
    let fileBuf: Buffer = Buffer.alloc(0);
    let mergeNum = 0;
    // console.log('fileUrls', fileUrls);
    try {
        for (let i = 0; i < fileUrls.length; i++) {
            const url = fileUrls[i];
            let fstat = statSync(url);
            if (fstat.size > size * 1000) {
                console.log(`${url} 大小为${fstat.size}, 不符合合并规则`);
                continue;// 只有小于size的文件，才能合并
            }
            if (fstat.isFile()) {
                console.log('开始写入==>', url);
                let tempUrl = ''
                if (url.indexOf(baseUrl) >= 0) {
                    let temp = join(prefix, url.substr(baseUrl.length))
                    temp = temp.replace(/\\/g, '\/');
                    console.log('head:', temp);
                    tempUrl = temp;
                } else {
                    continue;
                }
                if (outType == 'json') {
                    let obj = JSON.parse(readFileSync(url).toString());
                    let fileStr = JSON.stringify(obj);
                    mergedObj[tempUrl] = fileStr;
                } else if (outType == 'bin') {
                    let buf = readFileSync(url);
                    mergedObj[tempUrl] = { start: fileBuf.length, end: fileBuf.length + buf.length };
                    fileBuf = Buffer.concat([fileBuf, buf]);
                }
                mergeNum++;

                if (needDelFile) {
                    unlinkSync(url);
                }
            }
        }
        // console.log('mergeobj', mergedObj);

        let mergeStr = JSON.stringify(mergedObj);
        if (outType == 'json') {
            writeFileSync(join(out, fn), mergeStr)
        } else if (outType == 'bin') {
            let mergeStrBuf = Buffer.from(mergeStr);
            console.log('mergeStrBuf', mergeStrBuf.length);

            let file = Buffer.alloc(4)
            file.writeUInt32LE(mergeStrBuf.byteLength);
            file = Buffer.concat([file, mergeStrBuf, fileBuf])
            writeFileSync(join(out, fn), file)

        }
        console.log(`==>此次共合并 ${mergeNum} 个文件<==`);

        complete()
    } catch (e) {
        console.log(e);
    }
}

export function merge(path: string, exts: string[], out: string, prefix = '', fn = '', delFile = 'false', outType = 'json', size = 0) {
    let files = [];
    getAllFiles(path, files, exts);

    mergeFiles(files, out || path, path, prefix, fn, delFile, outType, size);
}


function complete() {

    console.log('+------------------------+');
    console.log('|      merge finish!     |');
    console.log('+------------------------+\n');

}